package com.huakai.springenv.basic;

public class VolatileExample1 {
    
    // 使用volatile关键字修饰共享变量
    private volatile boolean flag = true;

    public static void main(String[] args) {
        VolatileExample1 example = new VolatileExample1();

        // 创建一个线程修改flag的值
        Thread writerThread = new Thread(() -> {
            try {
                Thread.sleep(1000); // 模拟一些工作
                example.flag = false; // 修改flag的值
                System.out.println("Flag has been set to false");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        // 创建一个线程监视flag的变化
        Thread readerThread = new Thread(() -> {
            while (example.flag) {
                // 等待flag的变化
            }
            System.out.println("Detected flag change, exiting...");
        });

        writerThread.start();
        readerThread.start();

        try {
            writerThread.join();
            readerThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
